﻿using Jy.Abp.Application;
using Jy.Abp.Extensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Identity;

namespace AbpProjectTemplate.System
{
    /// <summary>
    /// 安全日志
    /// </summary>
    [AppAuthorize(SystemManagementPermissions.Log.SecurityLog)]
    public class SecurityLogAppService : AppService<IdentitySecurityLog, Guid>
    {
        public SecurityLogAppService(IRepository<IdentitySecurityLog, Guid> repository) : base(repository)
        {
        }

        /// <summary>
        /// 查询安全日志
        /// </summary>
        public async Task<PagedResultDto<SecurityLogDto>> GetListAsync(LogFilter filter)
        {
            var query = await Repository.GetQueryableAsync();
            var qr = query
                .WhereIf(filter.BeginDate.HasValue, t => t.CreationTime >= filter.BeginDate)
                .WhereIf(filter.EndDate.HasValue, t => t.CreationTime < filter.EndDate)
                .WhereIf(filter.Keywords.HasValue(), t => t.UserName.Contains(filter.Keywords)
                                                       || EF.Functions.Like(nameof(t.ExtraProperties).ToString(), filter.Keywords))
                .ProjectTo<SecurityLogDto>(ObjectMapper);

            filter.SetDefaultSortIfNot(nameof(IdentitySecurityLog.CreationTime));
            return await CreatePagedResultAsync(qr, filter);
        }
    }
}
